package com.boruan.shengtangfeng.core.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.boruan.shengtangfeng.core.dao.IArticleCategoryDao;
import com.boruan.shengtangfeng.core.dao.IArticleCommentDao;
import com.boruan.shengtangfeng.core.dao.IArticleDao;
import com.boruan.shengtangfeng.core.dao.IFavoritesDao;
import com.boruan.shengtangfeng.core.dto.ArticleCategoryDto;
import com.boruan.shengtangfeng.core.entity.*;
import com.boruan.shengtangfeng.core.service.IArticleService;
import com.boruan.shengtangfeng.core.service.ILogService;
import com.boruan.shengtangfeng.core.service.INoticeService;
import com.boruan.shengtangfeng.core.utils.GlobalReponse;
import com.boruan.shengtangfeng.core.vo.ArticleCategoryVo;
import com.boruan.shengtangfeng.core.vo.ArticleCommentVo;
import com.boruan.shengtangfeng.core.vo.ArticleVo;
import com.boruan.shengtangfeng.core.vo.ToAuditArticleVO;
import com.boruan.shengtangfeng.core.vo.mapper.ArticleCategoryVoMapper;
import com.boruan.shengtangfeng.core.vo.mapper.ArticleCommentVoMapper;
import com.boruan.shengtangfeng.core.vo.mapper.ArticleVoMapper;
import com.boruan.shengtangfeng.core.vo.mapper.ToAuditArticleVoMapper;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.db.KeyHolder;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.base.Strings;

/**
 * @author liuguangqiang
 * @date 2016年8月10日 上午9:36:16
 */
@Service
@Transactional(readOnly = true)
public class ArticleService implements IArticleService {
    private static Logger logger = LoggerFactory.getLogger(ArticleService.class);
    @Autowired
    private IArticleDao articleDao;
    @Autowired
    private IFavoritesDao favoritesDao;
    @Autowired
    private IArticleCategoryDao articleCategoryDao;
    @Autowired
    private ILogService logService;
    @Autowired
    private INoticeService noticeService;
    @Autowired
    private IArticleCommentDao iArticleCommentDao;

    /**
     * 后台查询用户信息
     *
     * @author liuguangqiang
     * @date 2016年8月10日 上午9:36:16
     */
    @Override
    public Article findId(Long id) {
        return articleDao.unique(id);
    }

    @Override
    public Article findById(Long id) {
        return articleDao.findById(id);
    }


    @Override
    public void pageQuery(PageQuery<Article> pageQuery, Article article) {
        pageQuery.setParas(article);
        articleDao.pageQuery(pageQuery);
    }

    /**
     * 分页查询待审核文章
     *
     * @param pageQuery
     */
    @Override
    public void pageToAuditArticle(PageQuery<Article> pageQuery) {
        articleDao.pageToAuditArticle(pageQuery);
    }

    /**
     * 过去一分钟待审核的文章
     *
     * @param article
     * @return
     */
    @Override
    public List<Article> newCheck(Article article) {
        return articleDao.newCheck(article);
    }


    @Override
    @Transactional(readOnly = false)
    public boolean save(Article article) {
        try {
            if (article.getId() == null) {
                KeyHolder kh = articleDao.insertReturnKey(article);
                article.setId(kh.getLong());
            } else {
                articleDao.updateById(article);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public List<Article> findByTemplate(Article article) {
        return articleDao.template(article);
    }

    @Override
    @Transactional(readOnly = false)
    public void deleteArticle(Long articleId, Long userId) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Article article = articleDao.single(articleId);
        article.setUpdateBy(userId.toString());
        article.setUpdateTime(new Date());
        article.setIsDeleted(true);
        articleDao.updateTemplateById(article);
        noticeService.addNotice(2, 1, articleId, article.getPublishId(), "内容被删除通知", "您于" + dateFormat.format(article.getCreateTime()) + "发表的文章" + "《" + article.getTitle() + "》，" + "因违反平台规定被删除");
        Log sysLog = new Log();
        sysLog.setContent("删除文章");
        sysLog.setCreateTime(new Date());
        sysLog.setOperater(userId);
        sysLog.setObjectId(articleId);
        sysLog.setLogType(Log.LogType.ADMIN);
        sysLog.setOperateType(Log.OperateType.DELETE);
        logService.save(sysLog);
    }

    @Override
    public void pageQueryCategory(PageQuery<ArticleCategory> pageQuery, ArticleCategory articleCategory) {
        pageQuery.setParas(articleCategory);
        articleCategoryDao.pageQuery(pageQuery);
    }

    @Override
    public List<ArticleCategory> getCategoryList(ArticleCategory articleCategory) {
        return articleCategoryDao.getList(articleCategory);
    }


    @Override
    public List<Article> findClosely(Article article) {
        return articleDao.findClosely(article);
    }


    // ================= 后台 ===================
    @Override
    @Transactional(readOnly = false)
    public void addArticle(Article po, Long userId) {

        po.setType(Strings.isNullOrEmpty(po.getImages()) ? 1 : po.getImages().split(",").length == 1 ? 2 : 3);

        if (null != po.getId()) {
//			po.setPublisher(user.getName());
//			po.setPublisherIcon(user.getHeadImage());
            po.setPublishDate(new Date());
            po.setIsDeleted(false);
            po.setUpdateBy(userId.toString());
            po.setUpdateTime(new Date());
            articleDao.updateTemplateById(po);
        } else {
            po.setPublishId(1L);
            po.setUploadType(0);
            po.setPublishDate(new Date());
            po.setCreateBy(userId.toString());
            po.setIsDeleted(false);
            po.setCreateTime(new Date());
            articleDao.insertTemplate(po);
        }

    }

    @Override
    public List<ArticleCategoryVo> getCategory() {
        ArticleCategory po = new ArticleCategory();
        po.setIsDeleted(false);
        return ArticleCategoryVoMapper.MAPPER.toVo(articleCategoryDao.getList(po));
    }

    @Override
    @Transactional(readOnly = false)
    public void updateArticle(Long articleId, Integer type, Long userId) {

        Article article = articleDao.unique(articleId);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Article po = new Article();
        po.setId(articleId);
        po.setUpdateBy(userId.toString());
        po.setUpdateTime(new Date());
        if (type == 0) {
            po.setStatus(1);
        } else if (type == 1) {
            po.setStatus(0);
        } else if (type == 2) {
            po.setRecommend(true);
        } else if (type == 3) {
            po.setRecommend(false);
        } else if (type == 4) {
            po.setIsDeleted(true);
            noticeService.addNotice(2, 1, article.getId(), article.getPublishId(), "内容被删除通知", "您于" + dateFormat.format(article.getCreateTime()) + "发表的文章" + "《" + article.getTitle() + "》，" + "因违反平台规定被删除");

        }
        articleDao.updateTemplateById(po);

    }

    @Override
    @Transactional(readOnly = false)
    public void saveCategory(ArticleCategory articleCategory) {
        if (articleCategory.getId() == null) {
            KeyHolder kh = articleCategoryDao.insertReturnKey(articleCategory);
            articleCategory.setId(kh.getLong());
        } else {
            articleCategoryDao.updateById(articleCategory);
        }
    }

    @Override
    public ArticleCategory getCategory(Long categoryId) {
        return articleCategoryDao.single(categoryId);
    }

    @Override
    public void pageQueryCategory(PageQuery<ArticleCategory> pageQuery, ArticleCategoryDto articleCategoryDto) {
        pageQuery.setParas(articleCategoryDto);
        articleCategoryDao.pageQuery(pageQuery);
    }


    /**
     * @return
     * @description: 获取关注人的文章
     * @Param
     * @author KongXH
     * @date 2020/8/18 10:59
     */
    @Override
    public void pageAttentionArticle(PageQuery<Article> pageQuery, Long userId) {
        pageQuery.setPara("userId", userId);
        pageQuery.setPara("searchNoBlack", userId);
        articleDao.pageAttentionArticle(pageQuery);
    }

    @Override
    public Long templateCount(Article article) {
        return articleDao.templateCount(article);
    }

    @Override
    public Long getFavoritesCount(Long userId) {
        return favoritesDao.getFavoritesArticleCount(userId);
    }

    @Override
    public void pageFavoritesArticle(PageQuery<Article> pageQuery, Long userId) {
        pageQuery.setPara("userId", userId);
        articleDao.pageFavoritesArticle(pageQuery);
    }

    @Override
    public void pageAccoladeArticle(PageQuery<Article> pageQuery, Long userId) {
        pageQuery.setPara("userId", userId);
        articleDao.pageAccoladeArticle(pageQuery);
    }

    /**
     * 审核端根据用户id查询用户的所有文章
     *
     * @param pageIndex
     * @param pageSize
     * @param userId
     * @return
     */
    @Override
    public GlobalReponse<PageQuery<ToAuditArticleVO>> getUserArticle(int pageIndex, int pageSize, Long userId,String keywords) {
        PageQuery<Article> pageQuery = new PageQuery<>();
        pageQuery.setPageNumber(pageIndex);
        pageQuery.setPageSize(pageSize);
        pageQuery.setPara("userId", userId);
        pageQuery.setPara("keywords", keywords);
        articleDao.getUserArticle(pageQuery);
        List<Article> list = pageQuery.getList();
        List<ToAuditArticleVO> vos = ToAuditArticleVoMapper.MAPPER.toVo(list);
        pageQuery.setList(vos);
        return GlobalReponse.success(pageQuery);
    }

    /**
     * 审核端根据文章id查看文章详情
     *
     * @param articleId
     * @return
     */
    @Override
    public GlobalReponse<ToAuditArticleVO> getArticleDetails(Long articleId) {
        Article single = articleDao.createLambdaQuery().andEq(Article::getId, articleId).single();
        if (single != null) {
            ToAuditArticleVO articleVO = ToAuditArticleVoMapper.MAPPER.toVo(single);
            if (single.getStatus() == 1) {
                List<ArticleComment> comments = iArticleCommentDao.createLambdaQuery().andEq(ArticleComment::getArticleId, single.getId()).andEq(ArticleComment::getStatus, 1).andEq(ArticleComment::getIsDeleted, false).select();
                if (comments != null) {
                    List<ArticleCommentVo> articleCommentVos = ArticleCommentVoMapper.MAPPER.toVo(comments);
                    articleVO.setComment(articleCommentVos);
                }
            }
            return GlobalReponse.success(articleVO);
        }
        return GlobalReponse.fail("查询失败");
    }

}